import React from 'react';
import { useRouter } from 'next/router';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { useChatStore } from '@/store/chat';
import BackButton from '@/components/common/BackButton';

const ChatHistoryPage: React.FC = () => {
  const router = useRouter();
  const { histories, currentService } = useChatStore();
  const messages = histories[currentService] || [];

  // Group messages by date
  const groupedMessages = messages.reduce((groups, message) => {
    const date = format(message.timestamp, 'yyyy-MM-dd', { locale: zhCN });
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(message);
    return groups;
  }, {} as Record<string, typeof messages>);

  const sortedDates = Object.keys(groupedMessages).sort((a, b) => 
    new Date(b).getTime() - new Date(a).getTime()
  );

  // Get the return URL based on the current service
  const getReturnUrl = () => {
    if (currentService === 'default') {
      return '/chat';
    }
    return `/service/${currentService}`;
  };

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header */}
      <div className="page-header">
        <div className="flex items-center">
          <BackButton href={getReturnUrl()} />
          <span className="text-lg font-medium text-gray-800">聊天记录</span>
        </div>
      </div>

      {/* History List */}
      <div className="page-content">
        {sortedDates.length === 0 ? (
          <div className="flex items-center justify-center h-full text-gray-500">
            暂无聊天记录
          </div>
        ) : (
          <div className="p-4 space-y-6">
            {sortedDates.map(date => (
              <div key={date}>
                <div className="text-sm text-gray-500 mb-3">
                  {format(new Date(date), 'MM月dd日', { locale: zhCN })}
                </div>
                <div className="space-y-3">
                  {groupedMessages[date].map(message => (
                    <div
                      key={message.id}
                      className={`p-4 rounded-lg ${
                        message.isBot 
                          ? 'bg-white border border-gray-100' 
                          : 'bg-blue-500 text-white'
                      }`}
                    >
                      <p className="text-sm leading-relaxed break-words">
                        {message.text}
                      </p>
                      <div className="mt-2 text-xs text-right text-gray-500">
                        {format(message.timestamp, 'HH:mm', { locale: zhCN })}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ChatHistoryPage;